<template>
  <div style="position: fixed;width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;">
    <Loading size="24px" vertical>获取授权中...</Loading>
  </div>
</template>

<script>
import {Loading} from 'vant';
import {getToken, getUserInfo, getTmpMock, getTmpMockMr} from '@api/auth'

export default {
  name: "callback",
  components: {
    Loading
  },
  data() {
    return {
      result: {}
    }
  },
  methods: {
    tmp_mock(email) {
      getTmpMock(email).then(res => {
        if (res.successful) {
          if (res.data.bu) {
            sessionStorage.setItem('bu', res.data.bu)
          }
          sessionStorage.setItem('email', res.data.email)
            window.history.back()
        } else {
          alert('暂无身份信息')
            window.history.back()
        }
      })
    },
    tmp_mock_mr(email) {
      getTmpMockMr(email).then(res => {
        if (res.successful) {
          // if (res.data.mrBu) {
          //   sessionStorage.setItem('bu', res.data.mrBu)
          // }
          if (res.data.mrEmail) {
            sessionStorage.setItem('email', res.data.mrEmail)
          }
        } else {
          alert('暂无身份信息')
        }
      })
    },
  },
  async mounted() {
    let code = this.$route.query.code
    if (code) {
      getToken({code: code}).then(res => {
        this.result = res
        if (res.successful) {
          let token = res.data.token
          if (token) {
            sessionStorage.setItem('access-token', token)
            sessionStorage.setItem('role', res.data.roleName)
            sessionStorage.setItem('bu', res.data.bu)
            getUserInfo().then(res => {
              if (res.successful) {
                sessionStorage.setItem('name', res.data.name)
                sessionStorage.setItem('avatar', res.data.thumb_avatar)
                if (res.data.bu) {
                  sessionStorage.setItem('bu', res.data.bu)
                  sessionStorage.setItem('email', res.data.email)
                  sessionStorage.setItem('origin_email',res.data.email)
                  this.tmp_mock_mr(res.data.email)
                  setTimeout(() => {
                      window.history.back()
                  }, 500)
                } else {
                  this.tmp_mock(res.data.email)
                }
              } else {
                alert('获取用户数据异常，请联系后台管理员。')
              }
            })
          } else {
            alert("获取用户token为空，请联系后台管理员验证用户信息。")
          }
        } else {
          alert("获取token接口异常，请联系后台管理员。")
        }
      })
    } else {
      alert('未获取到授权码，请联系后台管理员添加授权账号。')
    }
  }
}
</script>

<style scoped>

</style>